import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { isEqual, trim } from 'lodash';
import { connect } from 'umi';
import { useCustomCompareEffect } from 'react-use';
import { Button, Card, Form, Icon, message, Modal, Popconfirm, Select, Spin, Tooltip } from 'antd';

import { defaultFormatResult, useRequest } from '@/hooks';
import { isSuccess } from '@/utils/request';
import { BottomAction } from '@/components';
import BizIcon from '@/components/BizIcon';
import Pre from '@/components/Pre';
import If from '@/components/If';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import authHelper from '@/utils/auth/helper';

import { cpfService } from '@/services/salaryManage/salaryCalculateService';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import { pageTabProps } from '@/pages/SalaryManage/utils';
import { PROCESS_TYPE } from '@/pages/SalaryManage/utils/processUtil';
import {
    goToProcessApply,
    goToProcessDetail,
    goToCpfSettingLog,
    gotoCPFSettingInProgress
} from '@/pages/SalaryManage/utils/pageNavigateUtil';
import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import { OrganizationNameHead } from '@/pages/SalaryManage/components/OrganizationName';
import TwoColHeader from '@/pages/SalaryManage/components/TwoColHead';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import ProcessStatusTag from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/components/ProcessStatusTag';
import { insuranceFundFileProcessStatus as processStatus } from '@/pages/SalaryManage/enum';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';

import { getRangeDescription } from '../rangeDescription';
import TableWrapper from './TableWrapper';
import Note from './Note';
import DetailModal from './DetailModal';

// 已生效
const EFFECT_IN = 0;

// 按钮权限
const AUTH_CODE = {
    ADD: 'finance:salary:computation:social:cpf:add', // 新增
    EDIT: 'finance:salary:computation:social:cpf:edit', // 编辑
    DEL: 'finance:salary:computation:social:cpf:delete' // 删除
};

const wrapDataSource = (dataList, cpfId) => {
    if (!dataList || dataList.length === 0) {
        return [];
    }

    const result = [];
    dataList.forEach(detail => {
        const { startAge, startAgeSign, endAge, endAgeSign, cpfShares } = detail;
        if (cpfShares?.length > 0) {
            cpfShares.forEach((share, index) => {
                result.push({
                    ...share,
                    cpfId,
                    startAge,
                    startAgeSign,
                    endAge,
                    endAgeSign,
                    v_rowSpan: index === 0 ? cpfShares.length : 0
                });
            });
        }
    });

    return result;
};
const wrapperWithRowSpan = (children, record) => ({
    children,
    props: {
        rowSpan: record.v_rowSpan
    }
});

const tableColumn = operateConfig => {
    const rel = [
        {
            title: '雇员年龄（X)',
            dataIndex: 'vv_age_range',
            width: 142,
            render(text, record) {
                const { startAgeSign, endAgeSign } = record;
                const startAge = trim(record.startAge);
                const endAge = trim(record.endAge);

                return wrapperWithRowSpan(
                    <EmptyPlaceHolder value={getRangeDescription(startAge, startAgeSign, endAge, endAgeSign)} />,
                    record
                );
            }
        },
        {
            title: '雇员该自然月薪资总额（X)',
            dataIndex: 'vv_month_total',
            width: 185,
            render(text, record) {
                const { twStartAmtSign, twEndAmtSign } = record;
                const twStartAmt = trim(record.twStartAmt);
                const twEndAmt = trim(record.twEndAmt);

                return (
                    <EmptyPlaceHolder
                        value={getRangeDescription(twStartAmt, twStartAmtSign, twEndAmt, twEndAmtSign, '$')}
                    />
                );
            }
        },
        {
            title: '总的公积金缴交比例（雇员+雇主）',
            dataIndex: 'totalShare',
            // align: 'center',
            render(text) {
                return <Pre>{text}</Pre>;
            }
        },
        {
            title: '雇员公积金缴交比例',
            dataIndex: 'employeeShare',
            // align: 'center',
            render(text) {
                return <Pre>{text}</Pre>;
            }
        },
        {
            title: '雇主公积金缴交比例',
            dataIndex: 'companyShare',
            // align: 'center',
            render(text) {
                return <Pre>{text}</Pre>;
            }
        }
    ];

    if (operateConfig) {
        const { onEdit, onDelete, disabled } = operateConfig;

        rel.push({
            title: '操作',
            dataIndex: '',
            width: 100,
            fixed: 'right',
            render(text, record) {
                return (
                    <AutoDivider>
                        <If condition={authHelper.checkCode(AUTH_CODE.EDIT)}>
                            <Tooltip title="编辑">
                                <Button
                                    className={salaryStyle.operateIcon}
                                    onClick={() => onEdit(record)}
                                    disabled={disabled}
                                >
                                    <BizIcon type="listfunction_edit_icon_default" />
                                </Button>
                            </Tooltip>
                        </If>
                        <If condition={authHelper.checkCode(AUTH_CODE.DEL)}>
                            <Popconfirm
                                title="确定要删除吗？"
                                placement="bottomRight"
                                onConfirm={() => onDelete(record)}
                                disabled={disabled}
                            >
                                <Tooltip title="删除" placement="top">
                                    <Button className={salaryStyle.operateIcon} disabled={disabled}>
                                        <BizIcon type="DeleteIcon" />
                                    </Button>
                                </Tooltip>
                            </Popconfirm>
                        </If>
                    </AutoDivider>
                );
            }
        });
    }

    return rel;
};
const CPFSetting = ({ form, organizationCode, effect, cpfId }) => {
    const { getFieldDecorator } = form;

    const [loading, setLoading] = useState(false);
    const [pageModel, setPageModel] = useState({});
    const [dataSource, setDataSource] = useState([]);
    const [approveInfo, setApproveInfo] = useState({});
    const [selectedCpfId, setSelectedCpfId] = useState(null);
    const [resetVisible, setResetVisible] = useState(false);
    // 是否显示新增、编辑框
    const [detailModalVisible, setDetailModalVisible] = useState(false);
    const { data: cpfList } = useRequest(() => cpfService.getCpfList({ organizationCode }), { ...defaultFormatResult });
    const { run: getCpfDetailList } = useRequest(params => cpfService.getCpfDetailList(params), {
        ...defaultFormatResult,
        manual: true
    });

    const [cpfDetailModel, setCpfDetailModel] = useState(null);
    const selectCpfRef = useRef({});

    const search = useCallback(async () => {
        // 获取查询条件
        const getSearchCondition = () => form.getFieldsValue();
        const getPostData = searchCondition => ({
            ...searchCondition,
            effect,
            organizationCode
        });

        const searchCondition = getSearchCondition();

        if (!searchCondition.cpfId) {
            return;
        }

        setLoading(true);
        getCpfDetailList(getPostData(searchCondition))
            .then(responseData => {
                if (responseData) {
                    setPageModel(responseData);
                    setDataSource(wrapDataSource(responseData.details, responseData.id));
                }
            })
            .finally(() => setLoading(false));
    }, [effect, form, getCpfDetailList, organizationCode]);

    // 是否可编辑
    const resetAble = () => !!pageModel?.resetAble;
    // 是否可进入下一步
    const nextAble = () => !!pageModel?.nextAble;

    const cpfChange = value => {
        setSelectedCpfId(value);
    };

    const reset = () => {
        setResetVisible(true);
    };

    const doReset = () => {
        const searchCondition = form.getFieldsValue();

        cpfService
            .resetCpf(searchCondition)
            .then(response => {
                if (!isSuccess(response)) {
                    message.warn(response.msg);
                    return;
                }
                message.success('重置成功！');
                setResetVisible(false);
                search();
            })
            .finally(() => {});
    };

    const onNext = async () => {
        setLoading(true);
        const searchCondition = form.getFieldsValue();
        cpfService
            .validateBeforeApply({ cpfId: searchCondition.cpfId })
            .then(response => {
                setLoading(false);

                if (!isSuccess(response)) {
                    message.error(response.msg);
                    return;
                }
                goToProcessApply(
                    PROCESS_TYPE.SALARY_SET_CPF_APPLY,
                    { cpfId: searchCondition.cpfId, organizationCode },
                    '没有找到分类为【财务cpf档案流程】的流程，请先配置流程'
                );
            })
            .catch(response => {
                setLoading(false);
                message.error(response.msg);
            });
    };

    const onEdit = record => {
        const { cpfId: currentCpfId } = form.getFieldsValue();

        if (!currentCpfId) {
            message.error('请选择公积金档案类型！');
            return;
        }
        selectCpfRef.current = cpfList.find(item => item.id === currentCpfId) || {};
        setCpfDetailModel(record);
        setDetailModalVisible(true);
    };

    // 点击删除
    const onDelete = record => {
        console.log('record:', record);
        setLoading(true);
        cpfService
            .deleteCpfDetail({ id: record.id, cpfId: record.cpfId })
            .then(response => {
                if (isSuccess(response)) {
                    message.success('删除成功！');
                    search();
                    return;
                }
                message.error(response.msg);
            })
            .finally(() => setLoading(false));
    };

    const handleAdd = () => {
        const { cpfId: currentCpfId } = form.getFieldsValue();

        if (!currentCpfId) {
            message.error('请选择公积金档案类型！');
            return;
        }
        selectCpfRef.current = cpfList.find(item => item.id === currentCpfId) || {};
        setCpfDetailModel(null);
        setDetailModalVisible(true);
    };

    const handleDetailModalOk = () => {
        search().then(() => {});
        setDetailModalVisible(false);
    };

    useMemo(() => {
        if (cpfList?.length > 0) {
            setSelectedCpfId(cpfId || cpfList[0].id);
        }
    }, [cpfId, cpfList]);

    useCustomCompareEffect(
        () => {
            if (selectedCpfId && organizationCode) {
                search();
            }
        },
        [search, organizationCode, selectedCpfId],
        ([, ...prevCompareDeps], [, ...nextCompareDeps]) => isEqual(prevCompareDeps, nextCompareDeps)
    );

    useEffect(() => {
        if (selectedCpfId) {
            cpfService.getCpfApproveInfo({ cpfId: selectedCpfId }).then(response => {
                if (isSuccess(response)) {
                    setApproveInfo(response.data);
                }
            });
        }
    }, [selectedCpfId]);

    return (
        <PageHeaderWrapper type="success">
            <BaseSettingProvider organizationCode={organizationCode}>
                <Card
                    title={
                        <>
                            <span className={salaryStyle.mr8}>公积金档案</span>
                            {EFFECT_IN === effect ? (
                                <ProcessStatusTag status={pageModel?.processStatus} />
                            ) : (
                                <ProcessStatusTag status={pageModel?.processStatus} className={salaryStyle.ml8}>
                                    {approveInfo?.year && approveInfo?.month ? (
                                        <>
                                            (
                                            {`${approveInfo.year}-${approveInfo.month < 10 ? '0' : ''}${
                                                approveInfo.month
                                            }`}
                                            起)
                                        </>
                                    ) : null}
                                </ProcessStatusTag>
                            )}
                        </>
                    }
                    extra={
                        EFFECT_IN === effect ? (
                            <div
                                style={{
                                    display: 'flex',
                                    lineHeight: '31px'
                                }}
                            >
                                <OrganizationNameHead organizationCode={organizationCode} />
                                <Button
                                    onClick={() => goToCpfSettingLog(organizationCode)}
                                    className={salaryStyle.ml12}
                                >
                                    操作日志
                                </Button>
                            </div>
                        ) : (
                            <OrganizationNameHead organizationCode={organizationCode} />
                        )
                    }
                    {...pageTabProps()}
                >
                    <Spin spinning={loading}>
                        <TwoColHeader
                            left={
                                <Form layout="inline">
                                    <Form.Item className={salaryStyle.mr8}>
                                        {getFieldDecorator('cpfId', {
                                            initialValue: selectedCpfId
                                        })(
                                            <Select style={{ width: 170 }} onChange={cpfChange}>
                                                {(cpfList || []).map(cpfVo => (
                                                    <Select.Option key={cpfVo.id} value={cpfVo.id}>
                                                        {cpfVo.prName}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )}
                                    </Form.Item>

                                    <If condition={EFFECT_IN === effect}>
                                        <Button
                                            type="primary"
                                            ghost
                                            className={salaryStyle.mr8}
                                            onClick={() => {
                                                gotoCPFSettingInProgress(organizationCode, selectedCpfId);
                                            }}
                                        >
                                            待生效档案
                                        </Button>
                                    </If>

                                    <Button
                                        type="primary"
                                        ghost
                                        onClick={() =>
                                            goToProcessDetail({
                                                processDefinitionId: approveInfo?.processDefinitionId,
                                                processInstanceId: approveInfo?.processId
                                            })
                                        }
                                        disabled={!(approveInfo.processDefinitionId && approveInfo.processId)}
                                    >
                                        查看审批详情
                                    </Button>
                                </Form>
                            }
                            right={
                                <If condition={EFFECT_IN === effect && authHelper.checkCode(AUTH_CODE.ADD)}>
                                    <Button
                                        type="primary"
                                        onClick={() => handleAdd(true)}
                                        disabled={processStatus.APPROVING === pageModel?.processStatus}
                                    >
                                        <Icon type="plus" />
                                        新增
                                    </Button>
                                </If>
                            }
                            style={{ marginTop: 8 }}
                        />
                        <TableWrapper
                            columns={tableColumn(
                                EFFECT_IN === effect
                                    ? {
                                          onEdit,
                                          onDelete,
                                          disabled: processStatus.APPROVING === pageModel?.processStatus
                                      }
                                    : null
                            )}
                            dataSource={dataSource}
                            pagination={false}
                        />
                        <Note />

                        <If condition={EFFECT_IN === effect}>
                            <BottomAction>
                                <Button onClick={reset} disabled={!resetAble()}>
                                    重置
                                </Button>
                                <Button type="primary" onClick={onNext} disabled={!nextAble()}>
                                    下一步
                                </Button>
                            </BottomAction>
                            <Modal
                                visible={resetVisible}
                                title="重置"
                                okText="确定"
                                cancelText="取消"
                                onOk={doReset}
                                onCancel={() => setResetVisible(false)}
                                width={480}
                                centered
                            >
                                <div style={{ margin: '30px 20px' }}>
                                    重置后所有数据将回退到上次审批通过的结果，是否确定重置？
                                </div>
                            </Modal>
                        </If>

                        <If condition={detailModalVisible}>
                            <DetailModal
                                title={cpfDetailModel ? '编辑' : '新增'}
                                visible={detailModalVisible}
                                cpfModel={selectCpfRef.current}
                                cpfDetailId={cpfDetailModel?.id}
                                onlyUpdate={!!cpfDetailModel?.id}
                                onCancel={() => setDetailModalVisible(false)}
                                onOk={handleDetailModalOk}
                            />
                        </If>
                    </Spin>
                </Card>
            </BaseSettingProvider>
        </PageHeaderWrapper>
    );
};

export default connect((state, { location }) => ({
    organizationCode: location?.query?.organizationCode,
    effect: location?.query?.effect ?? EFFECT_IN,
    cpfId: location?.query?.cpfId
}))(Form.create({})(CPFSetting));
